extends Node2D

class_name CameraController

@onready var camera:Camera2D = $"../Camera2D"

var zoom_level:float
var camera_drag:bool = false
var camera_old_pos:Vector2 = Vector2.ZERO

var mouse_pos:Vector2
var mouse_screen_pos:Vector2
var mouse_screen_old_pos:Vector2

func _ready():
	zoom_level = camera.zoom.x
	pass

func _physics_process(delta):
	if GlobalConfig.enabal_ui: 
		return
	if camera_drag:
		camera.position = camera_old_pos - (mouse_screen_pos - mouse_screen_old_pos) * zoom_level
	pass
	
func _unhandled_input(event):
	if GlobalConfig.enabal_ui: 
		return
	if event is InputEventMouse:
		mouse_pos = get_global_mouse_position()
		mouse_screen_pos = event.position
		if event is InputEventMouseButton:
			if event.button_index == MOUSE_BUTTON_WHEEL_UP:
				if zoom_level < 2.5:
					zoom_level += 0.1
					zoomCamera()
				pass
			elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
				if zoom_level > 0.6:
					zoom_level -= 0.1
					zoomCamera()
				pass
			elif event.button_index == MOUSE_BUTTON_LEFT:
				if event.is_pressed():
					camera_drag = true
					mouse_screen_old_pos = mouse_screen_pos
					camera_old_pos = camera.position
				else:
					camera_drag = false
				pass
			
			pass
		pass
	#elif event is InputEventScreenTouch:
		#var ev = event as InputEventScreenTouch
		#ev.index
		#pass
	pass


func  zoomCamera():
	camera.zoom = Vector2(zoom_level,zoom_level)
	#camera.position += -(get_global_mouse_position() - mouse_pos)
	camera.force_update_scroll()
	pass
